<?php
/**
 * Lightweight game bootstrap and dispatcher
 *  
 * @author Matt Pike
 */
class GameBootstrap{
	
	public function __construct(){
		$this->loadCoreResources();
		$this->dispatcher();
	}
	
	private function loadCoreResources(){
		require_once("Config.php");
		//require_once("GameConfig.php");
		require_once("DirectoryManager.php");
		require_once("core/Request.php");
		require_once("core/Filter.php");
		require_once("core/Controller.php");
		require_once("core/exceptions/BadRequest.php");
		
		DirectoryManager::$pathSrc = str_replace("\\","/",dirname(__FILE__));
		DirectoryManager::$pathCore = DirectoryManager::$pathSrc."/core";
		DirectoryManager::$pathModels = DirectoryManager::$pathSrc."/models";
		DirectoryManager::$pathViews = DirectoryManager::$pathSrc."/views";
	}
	
	/**
	 * Load and dispatch request
	 */
	private function dispatcher(){
		//if(!Request::isAjaxRequest()){ @todo uncomment when set up!
		//	throw new BadRequest("Non AJAX request");
		//}
		
		$controller = Request::getWord("c");
		$action 	= Request::getWord("a");
		
		if(!$controller || !$action){
			throw new BadRequest("Invalid controller/action: c=$controller a=$action");
		}
		
		switch($controller){
			default:
				if(file_exists(DirectoryManager::$pathSrc."/controllers/{$controller}.php")){
					require_once(DirectoryManager::$pathSrc."/controllers/{$controller}.php");
					if(class_exists($controller,false) && is_subclass_of($controller,"Controller") && method_exists($controller,$action."Action")){
						echo call_user_func(array($controller,$action."Action"),$_GET);
						exit;
					}else{
						throw new BadRequest("Unsupported controller/action: c=$controller a=$action");
					}
				}else{
					throw new BadRequest("Unrecognised controller: ".$controller);
				}
				break;
		}
	}
}